/**
 *@description 用户登录后开启websock请求
 * */
import store from '../store'
import {Notification} from 'element-ui';
import {getTradeOnMessage} from './receiving'
import lang from '../i18n'
import axios from 'axios'
import mqtt from 'mqtt'
import db from '../../datastore'

let tradeLine = db.read().get("trades.lineNode").value();
let port = db.read().get("trades.port").value();
let phpurl = tradeLine[0].url
var client
const options = {
    reconnectPeriod: 1000, // 1000毫秒，两次重新连接之间的间隔
    connectTimeout: 40000, // 40 * 1000毫秒，等待收到CONNACK的时间
    clientId: 'pc' + Math.random().toString(16).substr(2, 8), // mqttjs_
    username: "",
    password: "",
    clean: true
}

let ws = null // websock
let heart = null // 心跳包定时器id
let isWrong = false // 标记是否密码错误
let isError = false // 标记是否连接错误
var temp = new Array(); // 重连数组

// 将重连信息移除
function removeTemp(obj) {
    console.log("重连信息")
    var id = obj.id;
    //将请求记录从 temp 中去掉
    for (var key in temp) {
        if (id == temp[key].id) {
            console.log("移除:" + temp[key].id);
            temp.slice(key, 1);
            break;
        }
    }
}

// 重连程序
function reconnect(obj) {
    console.log('重连开始')
    var id = obj.id;
    //这可以写更多的重连逻辑，比如 每次重连间隔的时间增加

    // 1 账号密码错误不用重连
    if (isWrong) {
        return;
    }

    // 不是连接错误，并且为正常断开，则不用重连
    if (!isError && !store.getters.trade) {
        return
    }

    if (obj.reloadtimes == 10) {
        //将请求记录从 temp 中去掉
        removeTemp(obj);
    } else {
        obj.reloadtimes++;
        console.log(obj.id + "交易ws连接将在" + obj.reloadtimes + " 秒 后自动重新链接");
        setTimeout(() => {
            initWebSocket(obj.id, obj.url, obj.data, obj.callback);
        }, obj.reloadtimes * 1000); //每次间隔时间递增
    }
}

// WebSocket打开回调
function wsOnOpen(e) {
    heart = window.setInterval(() => {
        // console.log('心跳包')
        wsSend('50;')
    }, 10000)
    // 连接成功，在store中标记连接状态
    isError = false
    store.dispatch('user/changeTradeStatu', true)
    isWrong = false;
    Notification({
        title: lang[store.getters.lang].tip.success,
        position: 'bottom-right',
        message: lang[store.getters.lang].login.lsf,
        offset: 120,
        type: 'success'
    });
}

// 发送WebSocket请求
function wsSend(parameter) {
    console.log(parameter)
    parameter = loginData.uid + ";" + parameter
    console.log(parameter)
    client.publish("weituo", parameter, {qos: 2})
}

// 发送WebSocket请求kefu
function wsSendkf(param, content) {
    console.log('client', client)
    client.publish(param, content, {qos: 2})
}

// 接收WebSocket返回信息
function wsOnMessage(topic, data) {
    // 接收消息，体现在store中
    let dataArr = data.split(';')
	//console.log("接收消息");
	//console.log(dataArr);
    // 其他请求接收处理
    getTradeOnMessage(dataArr)

    // if (topic.indexOf('chating/customerSer') != -1) {
    //     console.log('chating/customerSer', data, '客服消息')
    //     let num = (topic.split('/')).length - 1
    //     if (num == 2) {
    //         store.dispatch('user/getChatList', data)
    //     } else {
    //         let _data = JSON.parse(data)
    //         store.dispatch('user/updateChatList', _data)
    //     }
    // }
    //
    // // 获取客户对应客服
    // if (topic.indexOf('khkf') != -1) {
    //     console.log('topiclen', data, '客服消息')
    //     let kfid = 'kf' + data
    //     store.dispatch('user/updateKid', kfid)
    //     wsSend('chating/history/' + kfid, `${store.getters.uid}`)
    //     // 缓存的历史消息
    //     let _chatList = localStorage.getItem('chatList') ? JSON.parse(localStorage.getItem('chatList')) : []
    //     // _chatList = JSON.parse(arr)
    //     // console.log('_chatList', _chatList)
    //     if (_chatList) {
    //         store.dispatch('user/updateChatList0', _chatList)
    //     }
    //     client.subscribe(`chating/customerSer/${store.getters.uid}/${store.getters.kid}`, (error) => {
    //         if (!error) { // 接收消息 chating/customerSer/用户id
    //             console.log('客户接收消息订阅成功')
    //         } else {
    //             console.log('客户接收消息订阅失败')
    //         }
    //     })
    //     client.subscribe(`chating/hisCustomerSer/${store.getters.uid}/${store.getters.kid}`, (error) => {
    //         if (!error) { // 历史数据 chating/hisCustomerSer/用户id
    //             console.log('客户发送消息订阅成功')
    //         } else {
    //             console.log('客户发送消息订阅失败')
    //         }
    //     })
    //
    // }
}

// WebSocket关闭回调
function wsClose() {
    if (ws && store.getters.trade) {
        store.dispatch('user/changeTradeStatu', false)
        window.clearInterval(heart)
        isError = false
        heart = null
        client.end()
    } else {
        // eslint-disable-next-line prefer-promise-reject-errors
        console.log('websock对象不存在或未创建')
    }
}

let loginData = null;

let kftimer = null
function initWebSocket(id, url, data, callback) {
    try {
        client.end()
    } catch (e) {

    }
    loginData = data;
    options.username = 'yh_'+data.uid + '_pc';
    options.password = data.token;
    let total = 0
    let msg = ''
    client = mqtt.connect(url, options);
    client.on('connect', (e) => {
        console.log('msg', msg)
        if (msg === 'kicked') {
            console.log('禁止订阅')
            return
        }
        if (total === 15) {
            store.dispatch('user/updateReconnect', true)
            return
        }
        wsOnOpen()
        setTimeout(() => {
            client.subscribe(`fanhui_${loginData.uid}`, {qos: 2}, (error) => {
                if (!error) {
                    console.log('订阅成功')
                    // 初始化
                    wsSend("20;")
                    wsSend("22;")
                    wsSend("23;")
                    wsSend("24;")
                    wsSend("25;")
                    wsSend("28;")
                    wsSend("35;0;0;")
                    wsSend("36;")
                    wsSend("26;")
                } else {
                    console.log('订阅失败')
                }

                /*
				client.subscribe(`kflist/${loginData.uid}/#`, (error) => {
                    if (!error) {

                        client.publish(`customerSerOnline/${loginData.uid}`);

                        // 订阅消息回复
                        client.subscribe(`chating/customerSer/${loginData.uid}/#`, () => {
                            console.log("订阅1成功：" + `chating/customerSer/${loginData.uid}/#`)
                        })
                        // chating/hisCustomerSer/用户id  订阅历史消息
                        client.subscribe(`chating/hisCustomerSer/${loginData.uid}`, () => {
                            console.log("订阅2成功：" + `chating/hisCustomerSer/${loginData.uid}`)
                        })
                    }
                })
				*/
            })

        }, 200)
    })
    // 接收消息处理
    client.on('message', (topic, message) => {

        wsOnMessage(topic, message.toString())
    })
    // offline 断开
    client.on('offline', (error) => {
        console.log('=====', data.uid)

        axios.post(`${phpurl}${port}/index.php/checkonline`, { // http://khdjk-hz.tjanta.com:800/index.php/checkonline
            yh_id: data.uid,
            mark: 'pc'
        }).then(res => {
            if (res.data.msg === 'kicked') {
                client.end()
                store.dispatch('user/updateLogVisible', true)
                // store.dispatch("user/logout", false)
            }
            msg = res.data.msg
        })
    })
    // 断开发起重连
    client.on('reconnect', (error) => {
        total++
        console.log('正在重连:', error)
        console.log('重连次数：', total)
    })
    // 链接异常处理
    client.on('error', (error) => {
        console.log('连接失败:', error)
    })
}

export {
    wsClose,
    initWebSocket,
    wsSend,
    wsSendkf,
    wsOnMessage,
    client
}
